package com.boot.utils;

import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class AppRunner implements ApplicationRunner {

	private final Logger dataLogger = LoggerFactory.getLogger("[DATA_LOGGER]");

	private final static String URL = "http://pp.corpautohome.com/exper/getUserPortraitFormat?id=%s&appid=PP_APP_PUSH_SYS&labels=sex,age,marital_status,is_have,edu_level,replace_demand,customer_value,car_seri,purchase_purpose_list,platform_list,car_age,stage,car_brand,brand_list,sect_list,seri_list,level_list,manu_list,brand_loyalty_list,stickiness_level,new_old_list,purpow,energy_list,category_list,user_tour,hour_list,function_list,convert_level,concen_degree,car_list,carprice_list,loan_willing,city_level,car_num,confidence_level&type=user_id";

	private final Map<String, String> portraitMap = new HashMap<>();

	private AtomicInteger counter = new AtomicInteger(0);

	private BlockingQueue<String> lineQueue = new ArrayBlockingQueue<String>(10000);

	@Override
	public void run(ApplicationArguments args) throws Exception {
//		//log.info("xxxxxxxxxxxxx");
//		init();
//		processMain();
//
//		File f = ResourceUtils.getFile("D:\\u.txt");
//		Scanner s = new Scanner(f);
//		while (s.hasNextLine()) {
//			lineQueue.put(s.nextLine());
//		}
//		s.close();

	}

	private void processMain() {
		ExecutorService service = Executors.newFixedThreadPool(2);
		for (int i = 0; i < 2; i++) {
			service.execute(new Runnable() {
				@Override
				public void run() {
					while (true) {
						try {
							String line = lineQueue.poll(10, TimeUnit.SECONDS);
							if (line == null)
								break;
							if (line.trim().length() == 0)
								continue;

							process(line.trim());
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			});
		}
		service.shutdown();
		//waitAll(service);
	}

	private void waitAll(ExecutorService executor){
		try {
			boolean loop;
			do {    //等待所有任务完成
				loop = !executor.awaitTermination(2, TimeUnit.SECONDS);
			} while(loop);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	private void process(String line) {
		// if (counter.incrementAndGet() == 1) {
		// logTitle(line);
		// return;
		// }

		String userId = line.split("\t")[0];
		String url = String.format(URL, userId);
		String body = get(url);

		StringBuffer portrait = new StringBuffer(line);
		JSONObject result = JSON.parseObject(body).getJSONObject("result");
		for (String field : fields) {

			JSONArray attrs = result.getJSONArray(field);
			List list=Arrays.asList(fixLength);

			if(list.contains(field)){//取前三个值 拆为3列

				for(int i=0;i<3;i++){
					StringBuffer attr = new StringBuffer();
					if(attrs != null && attrs.size() > 0 && i<=attrs.size()-1){
						String code = attrs.getJSONObject(i).getString("code");
						attr.append(code);
					}
					portrait.append("\t").append(attr);

				}

			}else {
				StringBuffer attr = new StringBuffer();
				if (attrs != null && attrs.size() > 0) {
					String code = attrs.getJSONObject(0).getString("code");
					attr.append(code);
				}
				portrait.append("\t").append(attr);
			}

		}
		dataLogger.info(portrait.toString());
	}

	private String get(String url) {
		String body = HttpUtil.reqGet(url);
		if (body == null) {
			//log.info("sleep 5s, retry..");
			try {
				TimeUnit.SECONDS.sleep(5);
			} catch (InterruptedException e) {
			}
			body = get(url);
		}
		return body;
	}

	private void logTitle(String prev) {
		StringBuffer portrait = new StringBuffer(prev);
		for (String field : fields) {
			portrait.append("\t").append(portraitMap.get(field));
		}
		dataLogger.info(portrait.toString());
	}

	private void init() {
		portraitMap.put("sex", "性别");
		portraitMap.put("age", "年龄");
		portraitMap.put("marital_status", "婚姻状况");
		portraitMap.put("is_have", "是否拥有车辆");
		portraitMap.put("edu_level", "教育水平");
		portraitMap.put("replace_demand", "置换偏好");
		portraitMap.put("customer_value", "价值等级");
		portraitMap.put("car_seri", "有车车系");
		portraitMap.put("purchase_purpose_list", "购车目的");
		portraitMap.put("platform_list", "平台偏好");
		portraitMap.put("car_age", "有车年限");
		portraitMap.put("stage", "购车阶段");
		portraitMap.put("car_brand", "有车品牌");
		portraitMap.put("brand_list", "品牌偏好");
		portraitMap.put("sect_list", "派系偏好");
		portraitMap.put("seri_list", "车系偏好");
		portraitMap.put("level_list", "级别偏好");
		portraitMap.put("manu_list", "厂商偏好");
		portraitMap.put("brand_loyalty_list", "品牌忠诚");
		portraitMap.put("stickiness_level", "用户粘性");
		portraitMap.put("new_old_list", "新车二手车偏好");
		portraitMap.put("purpow", "购车预算");
		portraitMap.put("energy_list", "能源偏好");
		portraitMap.put("category_list", "栏目偏好");
		portraitMap.put("user_tour", "旅游偏好");
		portraitMap.put("hour_list", "小时偏好");
		portraitMap.put("function_list", "活跃用户功能偏好");
		portraitMap.put("convert_level", "活跃用户购车转化周期");
		portraitMap.put("concen_degree", "活跃用户兴趣集中度");
		portraitMap.put("car_list", "活跃用户有车车型");
		portraitMap.put("carprice_list", "活跃用户汽车价格偏好");
		portraitMap.put("loan_willing", "贷款意愿");
		portraitMap.put("city_level", "城市等级");
		portraitMap.put("car_num", "车辆数");
		portraitMap.put("confidence_level", "置信度等级");
	}

	private final String[] fields = new String[] { "sex", "age", "marital_status", "is_have", "edu_level", "replace_demand", "customer_value",
			"car_seri", "purchase_purpose_list", "platform_list", "car_age", "stage", "car_brand", "brand_list", "sect_list", "seri_list",
			"level_list", "manu_list", "brand_loyalty_list", "stickiness_level", "new_old_list", "purpow", "energy_list", "category_list",
			"user_tour", "hour_list", "function_list", "convert_level", "concen_degree", "car_list", "carprice_list", "loan_willing", "city_level",
			"car_num", "confidence_level" };
	
	private final String[] fixLength = new String[] { "platform_list", "brand_list", "sect_list", "seri_list", "level_list", "manu_list", "brand_loyalty_list",
			"category_list", "hour_list", "function_list","carprice_list"  };

}
